package com.freestyle.common.utils;

//import com.freestyle.common.spring.modules.BaseModule;

import java.io.*;
import java.math.BigInteger;
import java.net.URI;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Util {
	public static String c_java_datetime_fmt = "yyyy-MM-dd HH:mm:ss";// "dd/MMM/yyyy
	public static String c_java_dttfmt = "dd/MMM/yyyy HH:mm:ss";
	public static String c_java_dttfmt_small = "dd/MMM/yyyy HH:mm";
	
	public static String c_java_datefmt = "yyyy-MM-dd";// "dd/MMM/yyyy";
	public static String c_sys_num_fmt = "#,###,###,##0";
	public static String c_sys_num_fmt_b = "#,###,###,###";
	public static String c_sys_amt_fmt = "##,###,##0.00";
	public static String c_sys_small_amt_fmt = "##,##0.00###";

	public static final String c_sql_date_fmt = "yyyy-MM-dd";// "DD/Mon/YYYY";
	public static final String c_sql_time_fmt = "HH24:MI";
	public static final String c_sql_datetime_fmt = "yyyy-MM-dd HH24:mm:ss";// "DD/Mon/YYYY
																			// HH24:MI";
	// SQL Format
	public static final String c_sql_num_fmt = "9,999,999,990";
	public static final String c_sql_amt_fmt = "99,999,990.99";
	public static final String c_sql_small_amt_fmt = "99,990.99999";

	public static PropertyResourceBundle c_message = null;
	public static String c_message_file = "";

	static public String getFileExtName(String fileName) {
		int idx = fileName.lastIndexOf(".");
		if (idx == -1)
			return "";
		File file = new File(fileName);
		String fineName = file.getName();
		String fileType = fileName.substring(idx + 1, fileName.length());
		return fileType;
	}

	public Util(String pvMessageFilePath) {
		c_message_file = pvMessageFilePath;
	}

	static public Date getCurrentTime() {
		Date tm = new Date();
		return tm;
	}

	static public Date getCurrentDate() {
		Date tm = deformatDatetime(dateToString(new Date(), c_java_datefmt), c_java_datefmt);
		return tm;
	}

	public static boolean isValidDate(String p_val, String p_pattern) {
		if (p_val == null)
			return false;

		try {
			SimpleDateFormat w_sdf = new SimpleDateFormat(p_pattern, Locale.ENGLISH);
			Date w_date = w_sdf.parse(p_val);
			String w_val = w_sdf.format(w_date);
			return (p_val.equalsIgnoreCase(w_val));
		} catch (ParseException e) {
			return false;
		}
	}

	public static boolean isInvalidDate(String p_val) {
		if (!(/* isValidDate(p_val, "dd/MM/yyyy") || */
		isValidDate(p_val, "dd/MMM/yyyy") || isValidDate(p_val, "d/MMM/yyyy") || isValidDate(p_val, c_java_datefmt)

		/*
		 * || isValidDate(p_val, "d/MM/yyyy") || isValidDate(p_val, "dd/M/yyyy")
		 * || isValidDate(p_val, "dd/M/yyyy") || isValidDate(p_val, "d/M/yyyy")
		 */))
			return true;
		return false;
	}

	static public String getCurrentTimeString() {
		Date dt = new Date();
		return datetimeToString(dt, null);
	}

	/**
	 * 把Uri转化成文件路径
	 */
	public static String uri2filePath(URI uri) {
		return uri.getPath();
	}

	static public Date deformatDate(String strDate) throws ParseException {
		try {
			if (strDate.contains("-")){
				return (new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH)).parse(strDate);
			}
			else{
				return (new SimpleDateFormat("yyyy/MM/dd", Locale.ENGLISH)).parse(strDate);
			}
		} catch (ParseException e) {
			try {
				return (new SimpleDateFormat(c_java_datefmt, Locale.ENGLISH)).parse(strDate);
			} catch (ParseException e1) {
				throw e1;
			}
		}
	}

	static public Date deformatDatetime(String strDate, String fmt) {
		try {
			if (fmt == null) {
				return (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH)).parse(strDate);
			} else {
				return (new SimpleDateFormat(fmt, Locale.ENGLISH)).parse(strDate);
			}
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	static public String getWeek(Date dt) {
		final String[] days = { "日", "一", "二", "三", "四", "五", "六" };
		Calendar cal = Calendar.getInstance();
		cal.setTime(dt);
		return "星期" + days[cal.get(Calendar.DAY_OF_WEEK) - 1];
	}

	static public boolean fileExists(String filename) {
		File f = new File(filename);
		return f.exists();
	}

	public static String getExtensionName(String filename) {
		if ((filename != null) && (filename.length() > 0)) {
			int dot = filename.lastIndexOf('.');
			if ((dot > -1) && (dot < (filename.length() - 1))) {
				return filename.substring(dot + 1);
			}
		}
		return filename;
	}

	/**
	 * 利用文件通道复制文件
	 *
	 * @param s
	 * @param t
	 */
	public static void fileChannelCopy(File s, File t) {
		FileInputStream fi = null;
		FileOutputStream fo = null;
		FileChannel in = null;
		FileChannel out = null;
		try {
			fi = new FileInputStream(s);
			fo = new FileOutputStream(t);
			in = fi.getChannel();// 得到对应的文件通道
			out = fo.getChannel();// 得到对应的文件通道
			in.transferTo(0, in.size(), out);// 连接两个通道，并且从in通道读取，然后写入out通道
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fi.close();
				in.close();
				fo.close();
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	static public int getFileSize(String filename) {
		File f = new File(filename);
		FileInputStream fis;
		int size = 0;
		try {
			fis = new FileInputStream(f);
			size = fis.available();
			fis.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return size;
	}

	static public Date getFileLastModify(String filename) {
		File f = new File(filename);
		Calendar cal = Calendar.getInstance();
		cal.setTimeInMillis(f.lastModified());
		return cal.getTime();
	}

	static public String getValue(String v1, String v2, String split) {
		if (v1.equals(v2))
			return v1;
		return v1 + " " + split + " " + v2;
	}

	static public void sleep(long tm) {
		try {
			Thread.sleep(tm);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/*
	 * static public void setActivityResult(HashMap params, String value) {
	 * params.put("_result", value); }
	 */

	static public Date day2String(int day) {
		// Date w_dt=new Date();
		Calendar w_cal = Calendar.getInstance();
		w_cal.add(Calendar.DAY_OF_YEAR, day);
		return w_cal.getTime();
	}

	static public int daysBetween(Date smdate, Date bdate) throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		smdate = sdf.parse(sdf.format(smdate));
		bdate = sdf.parse(sdf.format(bdate));
		Calendar cal = Calendar.getInstance();
		cal.setTime(smdate);
		long time1 = cal.getTimeInMillis();
		cal.setTime(bdate);
		long time2 = cal.getTimeInMillis();
		long between_days = (time2 - time1) / (1000 * 3600 * 24);

		return Integer.parseInt(String.valueOf(between_days));
	}

	public static String datetimeToString(Date dt, String fmt) {
		if (fmt == null) {
			return (new SimpleDateFormat(c_java_datefmt, Locale.ENGLISH)).format(dt);
		} else {
			return (new SimpleDateFormat(fmt, Locale.ENGLISH)).format(dt);
		}
	}

	public static String dateToString(Date dt, String fmt) {
		if (fmt == null) {
			return (new SimpleDateFormat(c_java_datefmt, Locale.ENGLISH)).format(dt);
		} else {
			return (new SimpleDateFormat(fmt, Locale.ENGLISH)).format(dt);
		}
	}

	static public Date fileDatetime2Datetime(long tm) {
		Calendar cal = Calendar.getInstance();
		cal.setTimeInMillis(tm);
		return cal.getTime();
	}

	static public String getPackageName(String className) {
		String[] w_items = className.split("\\.");
		StringBuffer w_ret = new StringBuffer();
		for (int i = 0; i <= w_items.length - 2; i++) {
			if (i < w_items.length - 2) {
				w_ret.append(w_items[i] + ".");
			} else {
				w_ret.append(w_items[i]);
			}
		}
		return w_ret.toString();
	}

	@SuppressWarnings("DefaultLocale")
	static public void searchFile(String pattern, File filepath, boolean deep, ArrayList<HashMap<String, String>> out) {
		File[] w_files = filepath.listFiles();
		if (w_files.length > 0) {
			for (File file : w_files) {
				if (file.isDirectory()) {
					if (file.canRead() && deep) {
						searchFile(pattern, file, deep, out);
					}
				} else {
					if (file.getName().indexOf(pattern) > -1
							|| file.getName().toUpperCase().indexOf(pattern.toUpperCase()) > -1) {
						HashMap<String, String> w_item = new HashMap<String, String>();
						w_item.put("name", file.getName());
						w_item.put("path", file.getPath());
						w_item.put("size", String.valueOf(file.length()));
						w_item.put("lastmodify", String.valueOf(file.lastModified()));
						out.add(w_item);
					}
				}
			}
		} else {
			if (filepath.getName().indexOf(pattern) > -1
					|| filepath.getName().toUpperCase().indexOf(pattern.toUpperCase()) > -1) {
				HashMap<String, String> w_item = new HashMap<String, String>();
				w_item.put("name", filepath.getName());
				w_item.put("path", filepath.getPath());
				w_item.put("size", String.valueOf(filepath.length()));
				w_item.put("lastmodify", String.valueOf(filepath.lastModified()));
				out.add(w_item);
			}
		}
	}

	public static byte[] toByteArray(InputStream input) throws IOException {
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		byte[] buffer = new byte[4096];
		int n = 0;
		while (-1 != (n = input.read(buffer))) {
			output.write(buffer, 0, n);
		}
		return output.toByteArray();
	}

	public static boolean byteSaveToFile(byte[] data, String file) {
		try {
			FileOutputStream outs = new FileOutputStream(file);
			outs.write(data);
			outs.close();
			return true;
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}

	}

	// 一维数组合并
	public static String[] getMergeArray(String[] al, String[] bl) {
		String[] a = al;
		String[] b = bl;
		String[] c = new String[a.length + b.length];
		System.arraycopy(a, 0, c, 0, a.length);
		System.arraycopy(b, 0, c, a.length, b.length);
		return c;
	}

	// 一维数组合并
	public static char[] getMergeArray(char[] al, char[] bl, int specbLeng) {
		char[] a = al;
		char[] b = bl;
		char[] c = new char[a.length + (specbLeng == 0 ? b.length : specbLeng)];
		System.arraycopy(a, 0, c, 0, a.length);
		System.arraycopy(b, 0, c, a.length, b.length);
		return c;
	}

	// 二维数组纵向合并
	public static String[][] unite(String[][] content1, String[][] content2) {
		String[][] newArrey = new String[][] {};
		List<String[]> list = new ArrayList<String[]>();
		list.addAll(Arrays.<String[]> asList(content1));
		list.addAll(Arrays.<String[]> asList(content2));
		return list.toArray(newArrey);
	}

	// 二维数组横向合并
	public static String[][] getMergeArray(String[][] al, String[][] bl) {
		if (al == null || al.length == 0)
			return bl;
		if (bl == null || bl.length == 0)
			return al;
		String[][] newArrey = null;
		// 根据数组的长度，判断要补全哪个数组
		if (al.length > bl.length) {
			newArrey = new String[al.length][];
			// 补全较短的数组
			String[][] temps = new String[al.length - bl.length][bl[0].length];
			for (int i = 0; i < temps.length; i++) {
				for (int j = 0; j < temps[0].length; j++)
					temps[i][j] = "";
			}
			String[][] btemp = unite(bl, temps);
			// 合并
			for (int k = 0; k < al.length; k++) {
				newArrey[k] = getMergeArray(al[k], btemp[k]);
			}
		} else {
			newArrey = new String[bl.length][];
			String[][] temps = new String[bl.length - al.length][al[0].length];
			for (int i = 0; i < temps.length; i++) {
				for (int j = 0; j < temps[0].length; j++)
					temps[i][j] = "";
			}
			String[][] atemp = unite(al, temps);
			for (int k = 0; k < bl.length; k++) {
				newArrey[k] = getMergeArray(atemp[k], bl[k]);
			}
		}
		return newArrey;
	}

	/**
	 * static <T> List<T> deepCopy(List<T> src) //关键代码 执行序列化和反序列化 进行深度拷贝
	 *
	 * @param src
	 * @return
	 * @throws IOException
	 * @throws ClassNotFoundException
	 *             <T>對象必須為序列化的Object
	 */

	public static <T> List<T> arrayListCopy(List<T> src) throws IOException, ClassNotFoundException {
		ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
		ObjectOutputStream out = new ObjectOutputStream(byteOut);
		out.writeObject(src);

		ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
		ObjectInputStream in = new ObjectInputStream(byteIn);
		@SuppressWarnings("unchecked")
		List<T> dest = (List<T>) in.readObject();
		return dest;
	}

	/***
	 * arrayListCopyToFile(List src,String p_savefilepath)
	 *
	 * @param src
	 *            --要保存的ArrayList對象
	 * @param p_savefilepath
	 *            保存位置
	 * @return 成功為true,失敗為false
	 */
	public static boolean arrayListCopyToFile(List src, String p_savefilepath) {
		try {
			ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(p_savefilepath));
			out.writeObject(src);
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	/**
	 * 從文檔講對象加載到ArrayList
	 *
	 * @param p_filepath
	 * @return
	 * @throws StreamCorruptedException
	 * @throws FileNotFoundException
	 * @throws IOException
	 * @throws ClassNotFoundException
	 */
	public static <T> List<T> arrayListCopyFromFile(String p_filepath)
			throws StreamCorruptedException, FileNotFoundException, IOException, ClassNotFoundException {
		ObjectInputStream in = new ObjectInputStream(new FileInputStream(p_filepath));
		@SuppressWarnings("unchecked")
		List<T> dest = (List<T>) in.readObject();
		return dest;
	}

	/***
	 *
	 * @param src
	 *            --要保存的對象
	 * @param p_savefilepath
	 *            保存位置
	 * @return 成功為true,失敗為false
	 */
	public static boolean ObjectCopyToFile(Object src, String p_savefilepath) {
		try {
			ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(p_savefilepath));
			out.writeObject(src);
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	/***
	 *
	 *            --要保存的對象
	 * @param p_filepath
	 *            保存位置
	 * @return
	 * @return 成功為true,失敗為false
	 */
	public static <T> Object objectCopyFromFile(String p_filepath)
			throws StreamCorruptedException, FileNotFoundException, IOException, ClassNotFoundException {
		ObjectInputStream in = new ObjectInputStream(new FileInputStream(p_filepath));
		@SuppressWarnings("unchecked")
		Object dest = in.readObject();
		return dest;
	}

	/*
	 * //关键代码 执行序列化和反序列化 进行深度拷贝，写法不同而已，作用一样 //个人习惯 怎么喜欢怎么来！ public List
	 * deepCopy(List src) throws IOException, ClassNotFoundException{
	 * ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
	 * ObjectOutputStream out = new ObjectOutputStream(byteOut);
	 * out.writeObject(src); ByteArrayInputStream byteIn = new
	 * ByteArrayInputStream(byteOut.toByteArray()); ObjectInputStream in =new
	 * ObjectInputStream(byteIn); List dest = (List)in.readObject(); return
	 * dest; }
	 */

	public static void createPath(String path) {
		File file = new File(path);
		if (!file.exists()) {
			if (!file.mkdirs()) {
				// Log.e("Util-createPath", "create path " + path + " failed.");
			}
		}

	}

	public enum CPUTYPE {
		ARM, MIPS, Intel
	};

	public static String fillNullStr(String s) {
		return s == null ? "" : s;
	}

	public static String fillNullStr(String s, String defaultText) {
		return s == null ? defaultText : s;
	}

	public static String checkString(String p_str) {
		if (p_str == null)
			return "";
		p_str = p_str.trim();

		// Special character handling for SQL
		for (int w_i = 0; w_i < p_str.length(); w_i++) {
			if (p_str.charAt(w_i) == '\\')
				p_str = p_str.substring(0, w_i) + "\\\\" + p_str.substring(++w_i);
			if (p_str.charAt(w_i) == '\'')
				p_str = p_str.substring(0, w_i) + "\\'" + p_str.substring(++w_i);
			if (p_str.charAt(w_i) == '%')
				p_str = p_str.substring(0, w_i) + "\\%" + p_str.substring(++w_i);
			if (p_str.charAt(w_i) == '_')
				p_str = p_str.substring(0, w_i) + "\\_" + p_str.substring(++w_i);
		}
		return p_str;
	}

	public static CPUTYPE getCpuType() {
		String arch = System.getProperty("os.arch");
		// String arch = System.getProperty("ro.product.cpu.abi");
		String arc = arch.substring(0, 3).toUpperCase();
		if (arc.equals("ARM")) {
			return CPUTYPE.ARM;
		} else if (arc.equals("MIP")) {
			return CPUTYPE.MIPS;
		} else if (arc.equals("X86") || arc.equals("I68")) {
			return CPUTYPE.Intel;
		}
		return CPUTYPE.ARM;
	}

	// Get MIME Type
	public static String getMIME(String p_fname) {
		String c_mime[][] = { { "txt", "text/plain" }, { "htm", "text/html" }, { "html", "text/html" },
				{ "gif", "image/gif" }, { "jpg", "image/jpeg" }, { "jpeg", "image/jpeg" }, { "png", "image/png" },
				{ "amr", "audio/amr" }, { "mp4", "video/mp4" }, { "bmp", "image/bitmap" },
				{ "doc", "application/msword" }, { "xls", "application/excel" }, { "pps", "application/powerpoint" },
				{ "ppt", "application/powerpoint" }, { "pdf", "application/pdf" },
				{ "zip", "application/x-zip-compressed" } };
		int m_count = 0;

		try {
			while (true) {
				if (p_fname.toLowerCase().endsWith(c_mime[m_count][0]))
					return c_mime[m_count][1];
				m_count++;
			}
		} catch (ArrayIndexOutOfBoundsException p_e) {
		}
		return "application/xdownload";
	}

	public static boolean isValidFilePath(String p_filepath) {
		if (p_filepath == null || p_filepath.equals(""))
			return false;

		if (p_filepath.startsWith("/etc") || p_filepath.startsWith("/live/db") || p_filepath.indexOf("..") != -1
				|| p_filepath.indexOf("//") != -1)
			return false;
		return true;
	}

	public static String X14encrypt(String p_plain) {
		try {
			MessageDigest w_md = MessageDigest.getInstance("SHA");
			w_md.update(p_plain.getBytes());
			byte[] w_digests = w_md.digest();
			return new BigInteger(1, w_digests).toString(16);
		} catch (Exception p_e) {
		}
		return p_plain;
	}

	/**
	 * 获取系统当前默认时区与指定时区的时间差.(单位:毫秒)
	 *
	 * @param timeZoneId
	 *            时区Id
	 * @return 系统当前默认时区与指定时区的时间差.(单位:毫秒)
	 */
	public static int getDiffTimeZoneRawOffset(String timeZoneId) {
		return TimeZone.getDefault().getRawOffset() - TimeZone.getTimeZone(timeZoneId).getRawOffset();
	}

	public static String X11checkString(String p_str) {
		if (p_str == null)
			return "";
		p_str = p_str.trim();

		// Special character handling for SQL
		for (int w_i = 0; w_i < p_str.length(); w_i++) {
			if (p_str.charAt(w_i) == '\\')
				p_str = p_str.substring(0, w_i) + "\\\\" + p_str.substring(++w_i);
			if (p_str.charAt(w_i) == '\'')
				p_str = p_str.substring(0, w_i) + "\\'" + p_str.substring(++w_i);
			if (p_str.charAt(w_i) == '%')
				p_str = p_str.substring(0, w_i) + "\\%" + p_str.substring(++w_i);
			if (p_str.charAt(w_i) == '_')
				p_str = p_str.substring(0, w_i) + "\\_" + p_str.substring(++w_i);
		}
		return p_str;
	}

	public static String X20getSysDate() {
		SimpleDateFormat c_sdf = new SimpleDateFormat(c_java_datefmt, Locale.ENGLISH);
		Calendar w_cal = Calendar.getInstance();
		return c_sdf.format(w_cal.getTime());
	}

	/***
	 * 截取子字符串
	 * 
	 * @param s
	 * @param start
	 *            ,最左边为1
	 * @param len
	 *            截取长度
	 * @return
	 */
	public static String subString(String s, int start, int len) {
		return s.substring(start - 1, start + len);
	}

	public static void setMessageFile(String pvFilePath) {
		setMessageFile(pvFilePath, false);
	}

	public static void setMessageFile(String pvFilePath, boolean pvReset) {
		if (pvReset) {
			c_message = null;
		}
		if (c_message != null)
			return;

		try {
			c_message = new PropertyResourceBundle(new InputStreamReader(
							new FileInputStream(pvFilePath)));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		c_message_file = pvFilePath;

	}
	
	// Messages Key Function
	/*public static String X10getMessage(String p_name) {
		String w_str = "&lt;" + p_name + "&gt;"; // Default Message

		// Ignore null entry
		if (p_name == null)
			return w_str;

		// Get pooled message object

		// Manual Reload
		if (p_name.equals("RELOAD") || c_message == null)
			setMessageFile(c_message_file);

		if (c_message != null) {
			// If cannot get message, create message object again
			try {
				return c_message.getString(p_name.trim());
			} catch (MissingResourceException p_e) {
				c_message = null;
				return "";
			}

			// w_str = c_message.getString(p_name.trim());
		}
		// return w_str;
		return "";
	}*/
	


	public static String toString(String pvJoinStr, String... pvList) {
		return toString(pvList, pvJoinStr);
	}

	public static String toString(List<String> pvList, String pvJoinStr) {
		if (pvList == null)
			return null;
		ArrayList<String> lvT=new ArrayList<String>(pvList);
		pvList=lvT;		
		// 删除空字符条目
		List lvTmp = new ArrayList();
		for (String item : pvList) {
			if (item == null || item.equals(""))
				continue;
			lvTmp.add(item);
		}
		pvList.clear();
		pvList.addAll(lvTmp);
		if (pvList.size() == 0)
			return "";
		if (pvList.size() == 1)
			return (String) pvList.get(0);
		StringBuilder sb = new StringBuilder();
		sb.append(pvList.get(0));
		for (int i = 1; i < pvList.size(); i++) {
			if (pvList.get(i).equals(""))
				continue;
			sb.append(pvJoinStr);
			sb.append(pvList.get(i));
		}
		return sb.toString();
	}
	public static String toJsStringObject(List<String> pvList, String pvJoinStr,boolean pvbSkipEmpty) {
		if (pvList == null)
			return null;
		ArrayList<String> lvT=new ArrayList<String>(pvList);
		pvList=lvT;		
		// 删除空字符条目
		List lvTmp = new ArrayList();
		for (String item : pvList) {
			if (pvbSkipEmpty&&(item == null || item.equals("")))
				continue;
			lvTmp.add(item);
		}
		pvList.clear();
		pvList.addAll(lvTmp);
		if (pvList.size() == 0)
			return "[]";
		StringBuilder sb = new StringBuilder();
		sb.append("\""+pvList.get(0)+"\"");
		for (int i = 1; i < pvList.size(); i++) {
			if (pvbSkipEmpty&& pvList.get(i).equals(""))
				continue;
			sb.append(pvJoinStr);
			sb.append("\""+pvList.get(i)+"\"");
		}
		return "["+sb.toString()+"]";
	}

	public static String toString(String[] pvList, String pvJoinStr) {
		if (pvList == null)
			return null;
		boolean lvAllnull = true;
		for (String item : pvList) {
			if (item != null) {
				lvAllnull = false;
				break;
			}
		}
		if (lvAllnull)
			return null;

		List<String> lvTmp = new ArrayList<String>();
		for (String item : pvList) {
			if (item == null || item.equals(""))
				continue;
			lvTmp.add(item);
		}
		pvList = lvTmp.toArray(new String[lvTmp.size()]);
		if (pvList.length == 1)
			return (String) pvList[0];
		if (pvList.length == 0)
			return "";
		StringBuilder sb = new StringBuilder();
		sb.append(pvList[0]);
		for (int i = 1; i < pvList.length; i++) {
			if (pvList[i].equals(""))
				continue;
			sb.append(pvJoinStr);
			sb.append(pvList[i]);
		}
		return sb.toString();
	}

	public static String runCmd(String pvCommandLine) {
		// System.out.println("------------------dirOpt()--------------------");
		StringBuilder sb = new StringBuilder();
		Process process;
		try {
			// 执行命令
			process = Runtime.getRuntime().exec(pvCommandLine);
			// 取得命令结果的输出流
			InputStream fis = process.getInputStream();
			// 用一个读输出流类去读
			BufferedReader br = new BufferedReader(new InputStreamReader(fis));
			String line = null;
			// 逐行读取输出到控制台
			while ((line = br.readLine()) != null) {
				sb.append(line + "\n");
			}
			return sb.toString();
		} catch (IOException e) {
			e.printStackTrace();
			return "";
		}

	}
	/***
	 * 获得周期列表 
	 * @param pvDate 当前日期
	 * @param pvPeriods 多个周期
	 * @param pvIsBack 往后推
	 * @param pvSortDesc 
	 * @return
	 */
	public static List<String> getPeriods(Date pvDate,int pvPeriods,boolean pvIsBack,boolean pvSortDesc){
		ArrayList<String> lvRet=new ArrayList<String>();
		Calendar lvCal=Calendar.getInstance();
		lvCal.setTime(pvDate);
		for (int i=1;i<=pvPeriods;i++){
			if (pvSortDesc){
				lvRet.add(0, Util.dateToString(lvCal.getTime(),"yyyyMM"));
			}
			else{
				lvRet.add(Util.dateToString(lvCal.getTime(),"yyyyMM"));
			}
			if (pvIsBack){
				lvCal.add(Calendar.MONTH, -1);	
			}
			else{
				lvCal.add(Calendar.MONTH, 1);
			}
		}
		return lvRet;
	}
	public static String removeTag(String htmlStr) {
		String regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>"; // script
		String regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>"; // style
		String regEx_html = "<[^>]+>"; // HTML tag
		//String regEx_space = "\\s+|\t|\r|\n";// other characters
		//String regEx_space = "\\s+|\t";// other characters
		//String regEx_cr = "\\s+|\r|\n";// other characters
		htmlStr=htmlStr.replace("\r\n", "\r");
		Pattern p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
		Matcher m_script = p_script.matcher(htmlStr);
		htmlStr = m_script.replaceAll("");
		Pattern p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
		Matcher m_style = p_style.matcher(htmlStr);
		htmlStr = m_style.replaceAll("");
		Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
		Matcher m_html = p_html.matcher(htmlStr);
		htmlStr = m_html.replaceAll("");
		/*Pattern p_space = Pattern.compile(regEx_space, Pattern.CASE_INSENSITIVE);
		Matcher m_space = p_space.matcher(htmlStr);
		htmlStr = m_space.replaceAll("&nbsp;");
		Pattern p_cr=  Pattern.compile(regEx_cr, Pattern.CASE_INSENSITIVE);
		Matcher m_cr= p_cr.matcher(htmlStr);
		htmlStr = m_cr.replaceAll("<br/>");*/
		htmlStr =htmlStr.replace(" ", "&nbsp;").replace("\r","<br/>");
		return htmlStr;
	}
	
	//效验  
    public static boolean sqlValidate(String str) {  
        str = str.toLowerCase();//统一转为小写  
        String badStr = "'|and|exec|execute|insert|select|delete|update|count|drop|*|%|chr|mid|master|truncate|" +  
                "char|declare|sitename|net user|xp_cmdshell|;|or|-|+|,|like'|and|exec|execute|insert|create|drop|" +  
                "table|from|grant|use|group_concat|column_name|" +  
                "information_schema.columns|table_schema|union|where|select|delete|update|order|by|count|*|" +  
                "chr|mid|master|truncate|char|declare|or|;|-|--|+|,|like|//|/|%|#";//过滤掉的sql关键字，可以手动添加  
        String[] badStrs = badStr.split("\\|");
        String[] lvWords = str.split(" ");
        for (int i = 0; i < badStrs.length; i++) {  
            //if (str.indexOf(badStrs[i]) >= 0) { 
        	for (int j=0;j<lvWords.length;j++) {
	        	if (lvWords[j].equals(badStrs[i])) {
	                return true;  
	            }  
        	}
        }  
        return false;  
    }
    public static String getClassName(Object obj) {
    	String lvsClassz=obj.getClass().getSimpleName();
    	return lvsClassz;
    }
}
